# -*- coding: utf-8 -*-

import argparse
import os

from flask import Flask, request, jsonify

TOKEN = "abc123"


def create_app():
    app = Flask(__name__,
                root_path=os.getcwd())

    @app.route('/Query', methods=['POST'])
    def query():
        print("--------- receive query request --------------")
        if request.content_type.startswith("application/json"):
            token = request.headers.get("Authorization").strip()
            if token != TOKEN:
                return jsonify({"IsError": True,
                                "Message": "Invalid Token",
                                "ErrorCode": -7})
            try:
                json_data = request.json
                if not isinstance(json_data, dict):
                    return jsonify({"IsError": True,
                                    "Message": "Invalid json data",
                                    "ErrorCode": -5})
            except Exception as e:
                return jsonify({"IsError": True,
                                "Message": "Invalid json data",
                                "ErrorCode": -6})
            bar_code = json_data.get("BARCODE")

            print(request.json)
            message = [
                {
                    "BARCODE": bar_code,
                    "MODEL_NAME": "TeslaModelX"
                }
            ]

            return jsonify({"Data": message,
                            "IsError": False,
                            "Message": "Success ",
                            "ErrorCode": 0})
        else:
            return jsonify({"IsError": True,
                            "Message": "Invalid content type",
                            "ErrorCode": -5})

    @app.route('/Upload', methods=['POST'])
    def upload():
        print("--------- receive write request --------------")
        if request.content_type.startswith("application/json"):
            token = request.headers.get("Authorization").strip()
            if token != TOKEN:
                return jsonify({"IsError": True,
                                "Message": "Invalid Token",
                                "ErrorCode": -7})
            try:
                json_data = request.json
                if not isinstance(json_data, dict):
                    return jsonify({"IsError": True,
                                    "Message": "Invalid json data",
                                    "ErrorCode": -5})
            except Exception as e:
                return jsonify({"IsError": True,
                                "Message": "Invalid json data",
                                "ErrorCode": -6})
            print(request.json)
            return jsonify({
                "IsError": False,
                "Message": "success",
                "ErrorCode": 0
            })
        else:
            return jsonify({"IsError": True,
                            "Message": "Invalid content type",
                            "ErrorCode": -5})

    return app


def main():
    parser = argparse.ArgumentParser(description="Simple MES Demo")
    parser.add_argument("--host",
                        default="127.0.0.1")
    parser.add_argument("--port",
                        default=8888)

    args = parser.parse_args()
    app = create_app()
    app.run(host=args.host, port=args.port, threaded=False, debug=False)


if __name__ == "__main__":
    exit(main())
